// pages/cart/component/cart.js
import { ComponentWithStore } from 'mobx-miniprogram-bindings'
import { userStore } from '../../store/userStore'
import { reqCartList, reqUpdateChecked, reqCheckAllCart, reqAddCart, reqDelCart } from '@/api/cart'
// 导入miniprogram-computed
const computedBehavior = require('miniprogram-computed').behavior
var timer = null
ComponentWithStore({

  behaviors: [computedBehavior],
  storeBindings: [
    {
      store: userStore,
      fields: ['token'],
    },
  ],

  // 组件的属性列表
  properties: {},
  // 组件的初始数据
  data: {
    cartList: [],
    timer: null,
    emptyDes: '还没有添加商品，快去添加吧～'
  },
  // 添加computed选项
  computed: {
    sum(data) {
      // 注意： computed 函数中不能访问 this ，只有 data 对象可供访问
      // 这个函数的返回值会被设置到 this.data.sum 字段中
      return data.cartList.length > 0 && data.cartList.every(item => item.isChecked === 1)
    },
    // 计算总价格
    price(data) {
      let calculate = 0
      data.cartList.forEach(item => {
        if (+item.isChecked === 1) {
          calculate += item.count * item.price
        }
      })
      return calculate
    }
  },

  // 组件的方法列表
  methods: {
    onShow() {
      this.getList()
      this.setEmptyDes()
    },
    setEmptyDes() {
      this.setData({
        emptyDes: this.data.token ? '还没有添加商品，快去添加吧～' : '您尚未登录，点击登录获取更多权益'
      })
    },

    // 更新购物车商品状态
    async onchangeCheck(e) {
      const checked = e.detail ? 1 : 0
      const { id, index } = e.target.dataset
      const res = await reqUpdateChecked(id, checked)
      this.setData({
        [`cartList[${index}].isChecked`]: checked
      })
    },

    // 获取列表
    async getList() {
      const { data } = await reqCartList()
      this.setData({
        cartList: data
      })
    },

    // 点击全选
    async onchangeAllCheck(e) {
      const { detail } = e
      let isChecked = detail ? 1 : 0
      let res = await reqCheckAllCart(isChecked)
      if (+res.code === 200) {
        let arr = [...this.data.cartList]
        arr.forEach(item => item.isChecked = isChecked)
        this.setData({
          cartList: arr
        })
      }
    },

    // 购物车数量
    changeBuyNum(e) {
      if (timer) {
        clearTimeout(timer)
      }
      timer = setTimeout(async () => {
        const newbuynum = e.detail > 200 ? 200 : e.detail
        const { id, index, oldbuynum } = e.target.dataset
        const reg = /^([1-9]|[1-9]\d|1\d{2}|200)$/
        if (!reg.test(newbuynum)) {
          return this.setData({
            [`cartList[${index}].count`]: oldbuynum
          })
        }
        const num = newbuynum - oldbuynum
        if (num !== 0) {
          const res = await reqAddCart({ goodsId: id, count: num })
          if (+res.code === 200) {
            this.setData({
              [`cartList[${index}].count`]: newbuynum,
              [`cartList[${index}].isChecked`]: 1

            })
          }
        }
      }, 500)
    },
    // 删除
    async deleteFn(e) {
      const type = await wx.modal({ title: '确认删除该商品？' })
      if (type) {
        const { id } = e.target.dataset
        const res = await reqDelCart(id)
        if (res.code === 200) {
          wx.toast({ title: '删除成功' })
          this.getList()
        }
      }

    },

    // 去结算
    submit() {
      if (this.data.price === 0) {
        return wx.toast({
          title: '请先选择商品'
        })
      }
      wx.navigateTo({ url: '/modules/orderPayModule/pages/order/detail/detail' })
    }

  }
})
